import os
import uuid
from fastapi import APIRouter, Depends, HTTPException, status, Query, UploadFile
from ...utils.response_json import Success, SuccessExtra

UPLOAD_DIR = "application/static/images/goods"

app = APIRouter()

@app.post("/upload")
async def upload_goods_image(file: UploadFile):
    print(file)
    if not os.path.exists(UPLOAD_DIR):
        os.makedirs(UPLOAD_DIR)
    # if file.content_type not in ["image/jpeg", "image/png", "image/gif"]:
    #     raise HTTPException(status_code=400, detail="Invalid image format")
    # 生成唯一文件名
    file_ext = file.filename.split('.')[-1]
    new_name = f"{uuid.uuid4()}.{file_ext}"
    save_path = os.path.join(UPLOAD_DIR, new_name)
    with open(save_path, "wb") as f:
        content = await file.read()
        f.write(content)
    result = {"url": f"http://localhost:8000/static/images/goods/{new_name}", "name": new_name}
    return Success(data=result, msg="上传成功")